package pers.ijfxu.testngext.utils;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;

import java.io.*;
import java.util.Map;

public class BeetlUtils {
    /**
     * 将资源路径下指定文件夹内所有的文件渲染到资源路径下
     *
     * @param parentPath 需要渲染的文件所在的文件夹名称
     * @param datas 存放渲染的数据变量
     * @author ijfxu
     * @since 2022/10/22 下午2:36
     */
    public static <T extends Map> void render(String parentPath,T datas)  {
        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(parentPath);
        Configuration cfg = null;
        try {
            cfg = Configuration.defaultConfiguration();
        } catch (IOException e) {
            e.printStackTrace();
        }
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        File pfile = new File(PathUtils.getResource(parentPath));
        for(String file:pfile.list()){
            Template tmp = gt.getTemplate(file);
            tmp.binding(datas);
            BufferedWriter wr = null;
            try {
                wr = new BufferedWriter(new FileWriter(PathUtils.getResource(file)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            tmp.renderTo(wr);
            System.out.println("==========render file:"+file+" over!!!");
        }
    }


}
